package com.jinjia.ordersys.util;

import com.alibaba.fastjson.JSONObject;
import com.jinjia.ordersys.vo.AccessTokenVo;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 微信工具类
 * @Param:
 * @return:
 * @Author: fenghouzhi
 * @Date: 2:07 PM 2018/10/9
 */
@Slf4j
public class WeChatUtil {

    /**
     * 全局静态access_token对象
     */
    public static AccessTokenVo ACCESSTOKENVO = null;

    /**
     * 获取access_token对象
     */
    public static String getAccesstoken() {

        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("grant_type", ConstantUtil.CLIENT_CREDENTIAL);
        paramMap.put("appid", ConstantUtil.APP_ID);
        paramMap.put("secret", ConstantUtil.APP_SECRET);

        try {
            String responseData = HttpRequestUtil.httpGet(ConstantUtil.WEIXIN_TOKEN, paramMap, null);
            AccessTokenVo tokenVo = JSONObject.parseObject(responseData, AccessTokenVo.class);
            if (tokenVo != null) {
                ACCESSTOKENVO = tokenVo;
                int currentTime = DateUtil.getSecondTimestamp(new Date());
                ACCESSTOKENVO.setExpires_in(currentTime + ACCESSTOKENVO.getExpires_in());
            }
            log.info("AccessTokenVo:     " + ACCESSTOKENVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ACCESSTOKENVO.getAccess_token();
    }

    /**
     * access_token过期检测
     */
    public static String overdueDetection() {
        int currentTime = DateUtil.getSecondTimestamp(new Date());
        if (currentTime > ACCESSTOKENVO.getExpires_in()) {
            log.info("access_token过期，重新请求!");
            return getAccesstoken();
        } else {
            log.info("access_token还未过期，继续使用!");
            return ACCESSTOKENVO.getAccess_token();
        }
    }

}